import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from "@angular/common/http";
import { HttpHeaders } from "@angular/common/http"
import { registerLocaleData } from '@angular/common';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login-component',
  templateUrl: './login-component.component.html',
  styleUrls: ['./login-component.component.css']
})
export class LoginComponentComponent implements OnInit {
  myForm!: FormGroup;
  userName!: AbstractControl;
  password!: AbstractControl;
  formGroup!: FormGroup;
  public anyList: any;
  http: any;

  constructor(private fb: FormBuilder, private authService: AuthService) {
    this.myForm = this.fb.group(
      {
        'userName': ['', Validators.compose([Validators.required,
        Validators.minLength(7), Validators.pattern(/^zime/)])],
        'password': ['', Validators.compose([Validators.required,
        Validators.minLength(6)])]
      }
    );
    this.userName = this.myForm.controls['userName'];
    this.password = this.myForm.controls['password'];
  }

  onSubmit(value: any) {
    console.log(value);
    const username = this.formGroup.get('username').value;
    const password = this.formGroup.get('password').value;

    console.log("password:" + password);

    console.warn(this.formGroup.get('username').value);
    this.register();
  }

  ngOnInit(): void {
    this.formGroup = new FormGroup({
      username: new FormControl(''),
      password: new FormControl('')
    });
    console.info(this.formGroup.value);
  }

  // constructor(private http: HttpClient) { }
  // onSubmit() {
  //   // TODO: Use EventEmitter with form value
  // const username = this.formGroup.get('username').value;
  // const password = this.formGroup.get('password').value;

  // console.log("password:" + password);

  // console.warn(this.formGroup.get('username').value);
  // this.register();
  // }

  // ngOnInit(): void {
  //   this.formGroup = new FormGroup({
  //     username: new FormControl(''),
  //     password: new FormControl('')
  //   });
  //   console.info(this.formGroup.value);
  // }

  register() {
    const headers = new HttpHeaders().set("Content-type", "application/json; charset=UTF-8");
    //console.info(headers);
    this.http.post("http://localhost:4200/login", this.formGroup.value)
      .subscribe(res => {
        console.log(1)
        console.log(res)
        // localStorage.setItem('token',res.headers.get('Authorization'));
      })
  }
  // constructor(private authService: AuthService) { }

  login() {
    this.authService.login();
  }

}
